// fetch.js
import { reactive } from "vue";
import fetch from "@/utils/request";
import { ElMessage } from "element-plus";
import { isObject, isArray, parseTemplate } from "@/utils/tools";
export async function useFetch(config) {
  let {
    successMsg,
    errorMsg = "网络异常，请稍后重试！",
    resultMsgKey = "resultMsg",
    url,
    method,
    params = {},
    fields, // 参数的取值字段
    beforeExcuteJs,
    afterExcuteJs,
    beforeExcuteJsStr,
    afterExcuteJsStr,
    responseKey, // 响应数据字段
    responseType = "json", // 响应类型，默认json
    downloadFormat, // 下载时，文件格式
    downloadNameField, // 下载时，文件名字段
    successLogic,
    responseStatusKey = 'returnCode', // 响应成功的key
    successCode = '0', // 响应成功的code
    fetchMsg, // 请求之后，提示
  } = config || {};
  if (!url) {
    throw new Error("请配置请求地址！");
  } else {
    url = parseTemplate(url, params);
  }

  if (!method) {
    throw new Error("请配置请求方式！");
  }
  let body = reactive({});
  let error;
  let response;
  let data = {};
  try {
    /* 请求之前，处理params 先处理，再过滤 */
    if (beforeExcuteJs) {
      params = beforeExcuteJs(params);
    }
    /* 根据配置处理参数 */
    if (isObject(params)) {
      fields?.length
        ? fields.forEach((item) => {
            data[item] = params[item] || undefined;
          })
        : (data = params);
    } else if (isArray(params)) {
      params.map((el, i) => {
        data[i] = {};
        fields?.length
          ? fields.forEach((item) => {
              Object.assign(data[i], { [item]: el[item] || undefined });
            })
          : (data = params);
      });
    }
    if (beforeExcuteJsStr) {
      try {
        const evaluate = new Function("obj", `return ${beforeExcuteJsStr}`);
        data = evaluate(data);
      } catch (error) {
        console.error(
          "requset error",
          `配置项：${beforeExcuteJsStr}; 错误原因：${error}; 请确保上下文数据完整性;`
        );
      }
    }
    const type = !method || method.toLowerCase() === "post" ? "data" : "params";
    response = await fetch({ url: url, method, [type]: data, responseType: responseType });
    // console.log("response", response, responseKey);
    if (fetchMsg) {
      ElMessage.info(fetchMsg);
    }
    if(responseType !== 'json') {
      const blobFile = new Blob([response]);
      const blobUrl = URL.createObjectURL(blobFile);
      const a = document.createElement('a'); //创建一个a标签
      a.href = blobUrl;
      a.download = `${data[downloadNameField]}${downloadFormat}` || 'file';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);  //a标签上加上链接，并触发点击时间，下载数据
      URL.revokeObjectURL(blobUrl); // 释放 URL 对象
      return
    }
    response["request"] = data;
    body = responseKey ? response[responseKey] : response;
    /* 返回结果后处理result */
    if (afterExcuteJs) {
      data = afterExcuteJs(body);
    }
    
    if (afterExcuteJsStr) {
      try {
        const evaluate = new Function("obj", `return ${afterExcuteJsStr}`);
        body = evaluate(body);
      } catch (error) {
        console.error(
          "response error",
          `配置项：${afterExcuteJsStr}; 错误原因：${error}; 请确保上下文数据完整性;`
        );
      }
    }

    /* 根据成功逻辑  或者  配置成功提示语时  才提醒成功 */
    let isSuccess = successLogic ? new Function('obj', `return ${successLogic}`)({...config, ...body}) : false;
    if (isSuccess || successMsg) {
      ElMessage.success(successMsg || response[resultMsgKey] || "请求成功！");
    
    }
  } catch (e) {
    /* if(responseType !== 'json') {
      if (fetchMsg) {
        ElMessage.info(fetchMsg);
      }
      const blobData = e;
      const blobFile = new Blob([blobData]);
      const blobUrl = URL.createObjectURL(blobFile);
      const a = document.createElement('a'); //创建一个a标签
      a.href = blobUrl;
      a.download = `${data[downloadNameField]}${downloadFormat}` || 'file';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);  //a标签上加上链接，并触发点击时间，下载数据
      URL.revokeObjectURL(blobUrl); // 释放 URL 对象
    } else { */
      const res = e?.response;
      error = {
        status: res?.status,
        code: res?.data[responseStatusKey],
        message: res?.data[resultMsgKey],
        isError: true,
      };
      if (error?.code != successCode) {
        console.error(
          "fetch error",
          `配置内容：${JSON.stringify(config)}；接口状态：${JSON.stringify(
            error
          )};`
        );
        ElMessage.error(errorMsg || String(error?.message) || "请求失败！");
      }
    // }
  }
  return { body, error, result: body };
}

function download(data) {
  
}
